package cn.cvs.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义请求认证的Filter 实现Filter接口(servlet.Filter)
 */
public class AuthorizationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (httpRequest.getSession().getAttribute("currUser") == null){ //判断session中是否有登录用户
            httpResponse.setContentType("text/html;charset=utf-8");
            PrintWriter out = httpResponse.getWriter();
            System.out.println("请先登录!(Filter控制)");
            out.print("<script>alert('请先登录!(Filter控制)');" +
                    "location.href='"+httpRequest.getContextPath()+"/login"+"'</script>");
        }else{
            chain.doFilter(httpRequest,httpResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
